package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;
import util.SessionUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/addorder")
public class AddOrderServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        int state = -1;
        String msg = "未知错误";
        // 0.先得到前端的参数并效验
        String dids = req.getParameter("dids");
        String moneyStr = req.getParameter("money");
        if (StrUtil.isBlank(dids) || StrUtil.isBlank(moneyStr)) {
            // 无效参数
            msg = "无效参数";
        } else {
            // 1. 判断登录用户
            UserInfo userInfo = SessionUtil.getSessionUserInfo(req);
            if (userInfo != null) {
                // 2.先添加订单表（得到订单表id）
                Connection connection = DBUtil.getConnection();
                String sql = "insert into `order`(money,uid) values(?,?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setBigDecimal(1, new BigDecimal(moneyStr));
                statement.setInt(2, userInfo.getUid());
                int result = statement.executeUpdate();
                if (result >= 0) {
                    sql = "select @@IDENTITY as oid";
                    PreparedStatement statement2 = connection.prepareStatement(sql);
                    ResultSet resultSet = statement2.executeQuery();
                    if (resultSet.next()) {
                        int oid = resultSet.getInt("oid");
                        // 3.添加订单详情表
                        String[] didArr = dids.split(",");
                        result = 1;
                        for (String did : didArr) {
                            String addSql = "insert into `orderdetail`(oid,did) values(?,?)";
                            PreparedStatement statement1 = connection.prepareStatement(addSql);
                            statement1.setInt(1, oid);
                            statement1.setInt(2, Integer.valueOf(did));
                            result = statement1.executeUpdate();
                            if (result <= 0) {
                                // 操作失败
                                break;
                            }
                            DBUtil.close(null, statement1, null);
                        }
                        if (result >= 0) {
                            state = 200;
                            msg = "下单成功";
                            DBUtil.close(resultSet, statement, null);
                            DBUtil.close(null, statement2, connection);
                        } else {
                            state = -1;
                            msg = "部分订单添加成功";
                        }
                    }
                } else {
                    state = -1;
                    msg = "订单添加失败";
                }
            } else {
                msg = "未登录";
            }
        }
        resp.getWriter().println(
                JSONUtil.toJsonStr(new ResultData(state, "", msg))
        );
    }
}
